<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="40%" >
    <BasicForm @register="registerForm">
      <template #mssp="{ model, field }">
        <JCheckbox v-model:value="model[field]" dictCode="LICENCE" />
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../License.data';
  import { saveOrUpdate } from '../License.api';
  import { JSearchSelect } from '/@/components/Form/index';
  import { JCheckbox } from '/@/components/Form';
  import { getDictItems } from '@/api/common/api';
  import { message } from 'ant-design-vue';

  let checkOptions = ref<any>([]);
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  //checkOptions赋值,将选择的下拉框映射为一个数组arr[{'1','soar'},{'2','agent'}{'3','xxx'}]
  loadDictOptions();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    data.record.jsonStr = [];
    if (unref(isUpdate)) {
      if (data.record.mssp) {
        let arr = JSON.parse(data.record.mssp);
        console.log('arr', arr);
        console.log('checkOptions', checkOptions.value);
        const msspTrueValues = checkOptions.value.filter((item) => arr[item.label] === true).map((item) => item.value);
        console.log('numArr', msspTrueValues);
        data.record.jsonStr = msspTrueValues;
        // data.record.mssp = msspTrueValues;
        console.log('Final mssp value:', data.record.jsonStr);
      }
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  //根据字典code查询字典项
  //mssp选项查询
  function loadDictOptions() {
    //update-begin-author:taoyan date:2022-6-21 for: 字典数据请求前将参数编码处理，但是不能直接编码，因为可能之前已经编码过了
    let temp = 'LICENCE';
    if (temp.indexOf(',') > 0 && temp.indexOf(' ') > 0) {
      // 编码后 是不包含空格的
      temp = encodeURI(temp);
    }
    //update-end-author:taoyan date:2022-6-21 for: 字典数据请求前将参数编码处理，但是不能直接编码，因为可能之前已经编码过了
    getDictItems(temp).then((res) => {
      if (res) {
        checkOptions.value = res.map((item) => ({ value: item.value, label: item.text, color: item.color }));
        console.info('res', checkOptions.value);
      } else {
        console.error('getDictItems error: : ', res);
        checkOptions.value = [];
      }
    });
  }

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      console.log('values', values);
      const now = new Date();
      const issuedTime = new Date(values.issuedTime);
      const expiryTime = new Date(values.expiryTime);

      if(expiryTime <= now){
        message.error('过期时间必须大于当前时间');
        return;
      }
      if(expiryTime <= issuedTime){
        message.error('过期时间必须大于签发时间');
        return;
      }
      let params = {
        soar: false,
        agent: false,
        systemTenantMode: false,
        flow: false,
        ueba: false,
      };
      // let msspArr = values.mssp.split(',');
      let msspArr = (values.jsonStr || '').split(',');
      if (checkOptions.value.length > 0) {
        msspArr.forEach((item) => {
          checkOptions.value.forEach((option) => {
            if (item === option.value) {
              params[option.label] = true;
            }
          });
        });
      }
      // let params = {
      //     "soar":values.soar,
      //     "agent":values.agent,
      //     "systemTenantMode":values.systemTenantMode
      // }
      // values.mssp = JSON.stringify(params);
      // 关键修改：不再将mssp序列化为字符串，直接传递对象
      console.log('mssp before', values.mssp);
      values.mssp = JSON.stringify(params);
      console.log('mssp after', values.mssp);

      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, values });
    }catch (error){
      console.error('提交错误：', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped></style>
